import React from "react";
import { getBusinessData, changeContentField } from "src/utils/basic-business";
import { getSearchParams } from "src/utils/index";
import rFormItems from "./workstart-standard";
import Detail from "pages/commonListView/detail";
import WorkflowCommit from "../commonListView/commit/workflow-commit";
import Form from "pages/components/form";
import { NavBar, Button, TextArea } from "antd-mobile";
import Table from "../components/table";
import Btns from "pages/components/btns";
import { locationShape, historyShape, storeShape } from "src/propType";
import { guid } from "src/utils";
import axios from "src/api/index";
import dayjs from "dayjs";
import SignTable from "../commonListView/signTable";
import FileList from "../components/fileList";
import "./index.scss";

class Bidsection extends Detail {
    subForm = React.createRef();
    constructor(props) {
        super(props);
        const { store, location } = this.props;
        const UnitProject = location.pathname.indexOf("/WorkStartStandard/UnitProject/detail") > -1;
        this.state = {
            ...this.state,
            formData: {
                wbsId: null,
            },
            formItems: rFormItems(this, getBusinessData(store, location, "projId")),
            selectedOptions: getBusinessData(store, location, "options"),
            baseUrl2: "pqsprojDataSet",
            uploading: false,
            childTabType: null, //用于区分工程类型的字段和切换子表
            status: "",
            signTitle: "wbsName",
            typeValSelect: null,
            useTypeOfWorkflow: getBusinessData(store, location, "tableId"), //传递参数，工作流formType
            isHaveType: 0, // 默认不配置清单项
            typeIdOptions: [],
            optionOne: null,
            random: 0,
            uploadShow: false,
            moduleTableId: null,
            needSaveFormData: true, //开工标准化需要再审核的时候调用主表的保存

            columns: [
                {
                    headerName: "序号",
                    children: [
                        {
                            headerName: "",
                            colId: "cid",
                            field: "number",
                            width: 60,
                            rowDrag: false,
                            spanRows: ({ valueA, valueB }) => valueA === valueB,
                        },
                    ],
                },
                {
                    headerName: "评估项目",
                    headerClass: "ag-center-header",
                    rowDrag: false,
                    children: [
                        {
                            headerName: "",
                            field: "evalProj1",
                            wrapText: true,
                            width: 80,
                            rowDrag: false,
                            autoHeight: true,
                            spanRows: ({ valueA, valueB }) => valueA === valueB,
                        },
                        {
                            headerName: "",
                            field: "evalProj2",
                            wrapText: true,
                            width: UnitProject ? 180 : 80,
                            rowDrag: false,
                            autoHeight: true,
                            spanRows: ({ valueA, valueB }) => valueA === valueB,
                        },
                    ],
                },
                {
                    headerName: "评估标准",
                    headerClass: "ag-center-header",
                    children: [
                        {
                            headerName: "",
                            field: "evalCriteria",
                            minWidth: 200,
                            rowDrag: false,
                            wrapText: true,
                            autoHeight: true,
                        },
                    ],
                },
                {
                    headerName: "施工单位自评意见",
                    children: [
                        {
                            headerName: "施工单位自评意见",
                            field: "consOpinion",
                            rowDrag: false,
                            width: 160,
                            cellEditor: "agTextCellEditor",
                            editable: record => {
                                const { pactCode, page } = this.state;
                                const isEdit = record.data.isEdit;
                                if (page === "add") {
                                    return isEdit;
                                } else {
                                    return isEdit && pactCode.pactCode1;
                                }
                            },
                            singleClickEdit: true,
                        },
                    ],
                },
                {
                    headerName: "监理单位评估意见",
                    children: [
                        {
                            headerName: "监理单位评估意见",
                            field: "supOpinion",
                            rowDrag: false,
                            width: 160,
                            cellEditor: "agTextCellEditor",
                            editable: record => {
                                const { pactCode, page } = this.state;
                                const isEdit = record.data.isEdit;
                                if (page === "add") {
                                    return isEdit;
                                } else {
                                    return isEdit && pactCode.pactCode2;
                                }
                            },
                            singleClickEdit: true,
                        },
                    ],
                },
                {
                    headerName: "公司评估意见",
                    children: [
                        {
                            headerName: "公司评估意见",
                            field: "comOpinion",
                            width: 160,
                            rowDrag: false,
                            cellEditor: "agTextCellEditor",
                            editable: record => {
                                const { pactCode, page } = this.state;
                                const isEdit = record.data.isEdit;
                                if (page === "add") {
                                    return isEdit;
                                } else {
                                    return isEdit && pactCode.pactCode3;
                                }
                            },
                            singleClickEdit: true,
                        },
                    ],
                },
            ],
            dataSource: [],
        };
    }

    componentDidMount() {
        this.componentInit();
    }

    componentInit = () => {
        Promise.resolve(super.componentDidMount()).then(res => {
            this.setModules();
            this.initData();
        });
    };

    getTableList = noJoinId => {
        const { formData, page } = this.state;
        let data = {
            typeId: formData.projTypeId,
        };
        if (page === "edit" || page === "view" || page === "sign") {
            if (!noJoinId) {
                data.joinId = formData.kid;
            }
        }
        axios({
            method: "get",
            url: "/pqsstartWkInfo_list",
            data,
        }).then(res => {
            if (res.success) {
                let dataSource = res.data.map(item => {
                    item.kid = item.kid || guid();
                    item.joinId = item.joinId || formData.kid;
                    item.consOpinion = item.consOpinion || "";
                    item.supOpinion = item.supOpinion || "";
                    item.comOpinion = item.comOpinion || "";
                    item.isEdit = ["add", "edit", "sign"].includes(page) ? true : false;
                    return item;
                });
                this.setState({
                    dataSource,
                });
            }
        });
    };

    setModules = () => {
        const { store, location } = this.props;
        const moduleTableId = getBusinessData(store, location, "singleItem");
        const typeIdOptions = getBusinessData(store, location, "options");
        this.setState({
            formData: {
                moduleId: moduleTableId.tableId,
                moduleName: moduleTableId.modelName,
            },
            moduleTableId,
            typeIdOptions,
        });
    };

    initData = () => {
        const { store, location } = this.props;
        const params = getSearchParams(location.search);
        let { formData } = this.state;
        const moduleTableId = getBusinessData(store, location, "singleItem");
        const typeIdOptions = getBusinessData(store, location, "options");
        formData = {
            ...formData,
            moduleId: moduleTableId.tableId,
            moduleName: moduleTableId.modelName,
        };
        this.setState({
            formData,
            moduleTableId,
            typeIdOptions,
        });
        if (params.page === "add") {
            const selectedOptions = this.state.selectedOptions[0];
            const userData = store.user.userData;
            const optionOne = getBusinessData(store, location, "optionOne", selectedOptions?.value);
            formData = {
                ...formData,
                projTypeId: selectedOptions?.value, //业务id
                projTypeName: selectedOptions?.label, //业务label
                buildOrgId: "1", // 施工组织设计,主要人员变更,控制网评估申请使用
                buildOrg: "是",
                respUserId: userData.userId,
                respUserName: userData.name,
                addDate: new Date(),
                applyDate: new Date(),
                parentProjId: userData.projId,
                parentProjName: userData.projName,
            };
            // 明细表
            if (selectedOptions?.isSubTable) {
                formData = {
                    ...formData,
                    signKid: selectedOptions?.isSubTable,
                };
            }
            this.setState(
                {
                    formData,
                    childTabType: selectedOptions?.value,
                    useTypeOfWorkflow: selectedOptions?.value,
                    optionOne,
                },
                () => {
                    this.changeTypeListTable();
                    this.initResponseField();
                    this.setHiddenForm(userData);
                    // this.getTableList();
                    this.subForm.current?.form.setFieldsValue(formData);
                },
            );
        }
    };

    aftergetDetailData = resData => {
        const { store, location } = this.props;
        let formData = {
            ...resData,
            applyDate: resData.applyDate && dayjs(resData.applyDate).toDate(),
        };
        this.setState(
            {
                childTabType: formData.projTypeId,
                workflowModule: getBusinessData(
                    store,
                    location,
                    "workflowModule",
                    formData.projTypeId,
                ),
                useTypeOfWorkflow: formData.projTypeId,
                random: Math.random(),
            },
            () => {
                this.subForm.current?.form.setFieldsValue(formData);
                this.setHiddenForm();
                this.getTableList();
                this.changeTypeListTable();
            },
        );
    };

    changeTypeListTable = () => {
        let { typeIdOptions, formData, isHaveType } = this.state;
        if (typeIdOptions) {
            if (typeIdOptions.length === 1) {
                isHaveType = typeIdOptions[0].isHaveType;
            } else {
                if (formData.projTypeId > -1) {
                    // 业务类型值存在
                    const findItem = typeIdOptions.find(item => item.value == formData.projTypeId);
                    isHaveType = findItem && findItem.isHaveType;
                }
            }
            this.setState({
                isHaveType,
            });
        }
    };

    initResponseField = () => {
        const { formData, typeValSelect, selectedOptions, page } = this.state;
        // if (page === "add") {
        const mainWork = changeContentField(
            typeValSelect || selectedOptions[0],
            formData,
            "projTypeId",
        );
        this.setState(
            {
                formData: {
                    ...formData,
                    mainWork, //内容说明
                },
            },
            () => {
                this.subForm.current?.form.setFieldValue("mainWork", mainWork);
            },
        );
        // }
    };

    projTypeIdChange = val => {
        const { formData, page } = this.state;
        const { store, location } = this.props;
        const { label, value } = val;
        const newValue = {
            ...formData,
            projTypeId: value,
            projTypeName: label,
        };

        if (newValue.optionOne?.isSubTable) {
            newValue["signKid"] = newValue.optionOne.isSubTable ? 1 : null;
        }
        if (page === "add") {
            newValue["mainWork"] = changeContentField(
                newValue.typeValSelect,
                newValue,
                "projTypeId",
            );
        }
        this.setState(
            {
                formData: newValue,
                workflowModule: getBusinessData(store, location, "workflowModule", value),
                typeValSelect: val,
                optionOne: getBusinessData(store, location, "optionOne", value),
                childTabType: value,
                useTypeOfWorkflow: value,
            },
            () => {
                if (formData.projTypeId !== val.value) {
                    this.getTableList(val.value);
                }
                this.changeTypeListTable();
                this.setHiddenForm();
            },
        );
    };

    // 选择标段
    selectPact = pact => {
        let { formData } = this.state;
        if (pact) {
            formData["projName"] = pact.label;
            formData["projId"] = pact.value;
        } else {
            formData["projName"] = null;
            formData["projId"] = null;
        }
        this.setState(
            {
                formData: {
                    ...formData,
                },
            },
            () => this.initResponseField(),
        );
    };

    beforeSave = () => {
        let { formData, page, dataSource } = this.state;
        if (formData.applyDate && typeof formData.applyDate !== "string") {
            formData.applyDate = this.formatDateTime(formData.applyDate);
        }
        if (["add", "edit", "sign"].includes(page)) {
            dataSource = dataSource?.map(item => ({ ...item, isdel: 0 })) || [];
        }
        this.setState({
            status: "",
            formData: {
                ...formData,
                opinionJson: JSON.stringify(dataSource),
            },
        });
        return true;
    };

    render() {
        const {
            formItems,
            formData,
            options,
            columns,
            dataSource,
            baseUrl,
            useTypeOfWorkflow,
            workflowModule,
            useWorkflow,
            page,
            pageKid,
            title,
            hasSubTable,
            isHaveType,
            baseUrl2,
            moduleId,
            childTabType,
        } = this.state;
        const { store, location, history } = this.props;
        const { projId, pactId, userId } = store.user.userData;

        const btns = [
            {
                label: "确认审核",
                key: "1",
                fn: () => {
                    this.commitSign();
                },
                hidden: () => page !== "sign",
            },
            {
                label: "提交审核",
                key: "2",
                fn: () => {
                    this.commit();
                },
                hidden: () => !["edit", "add"].includes(page),
            },
            {
                label: "保存草稿",
                key: "3",
                fn: () => this.save(),
                hidden: () => !["edit", "add"].includes(page),
            },
            {
                label: "预览",
                key: "4",
                fn: () => this.toViewPdf(formData),
                hidden: () => page === "add",
            },
        ];

        const optionOne =
            getBusinessData(store, location, "optionOne", useTypeOfWorkflow) ||
            getBusinessData(
                store,
                location,
                "optionOne",
                getBusinessData(store, location, "tableId"),
            );

        let workflowModuleCur = workflowModule;
        if (useWorkflow) {
            workflowModuleCur = workflowModule + "-" + (formData[useWorkflow] || 1);
        }

        return (
            <div className="detail-container">
                <NavBar back="返回" onBack={() => this.props.history.go(-1)}>
                    {title}
                </NavBar>
                <Form
                    subtitle="基本信息"
                    formItems={formItems}
                    formData={formData}
                    projId={projId}
                    pactId={pactId}
                    options={options}
                    selectCallBack={{
                        selectPact: this.selectPact,
                        projTypeIdChange: this.projTypeIdChange,
                    }}
                    ref={this.subForm}
                    initSelect={page === "add"}
                    status={page}
                    formDisabled={["view", "sign"].includes(page)}
                >
                    {hasSubTable && (
                        <Table columns={columns} dataSource={dataSource} enableCellSpan={true} />
                    )}
                    {isHaveType ? (
                        <FileList
                            infoKid={pageKid}
                            url={baseUrl2}
                            moduleId={moduleId}
                            typeId={childTabType}
                            detailPage={page}
                            wbsId={formData.wbsId}
                            user={store.user.userData}
                        />
                    ) : null}
                </Form>
                <WorkflowCommit
                    ref={this.workflowRef}
                    baseUrl={baseUrl}
                    formData={formData}
                    optionOne={optionOne}
                    workflowModule={workflowModuleCur}
                    projId={projId}
                    userData={store.user.userData}
                    page={page}
                    kid={pageKid}
                    commitCallBack={this.commitCallBack}
                />
                <SignTable
                    ref={this.signRef}
                    optionOne={optionOne}
                    userId={userId}
                    addUserId={formData.addUserId}
                    kid={pageKid}
                    commitSignCallBack={this.commitSignCallBack}
                />
                <Btns btns={btns} size="large" block />
            </div>
        );
    }
}

Bidsection.propTypes = {
    store: storeShape,
    history: historyShape,
    location: locationShape,
};

export default Bidsection;
